<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/6/6 0006
 * Time: 下午 15:46
 */

namespace frontend\components\actions;


use common\models\c2\entity\Amoeba;
use common\models\c2\entity\UserInviteCode;
use Yii;
use yii\base\Action;
use yii\base\InvalidConfigException;
use yii\web\NotFoundHttpException;
use yii\web\Response;

class UserQRCodeAction extends Action
{

    public function run() {
        try {
            $qr = Yii::$app->get('qr');
        } catch (InvalidConfigException $e) {
            new NotFoundHttpException($e->getMessage());
        }

        $params = Yii::$app->request->get();

        $user = Yii::$app->user->currentUser;
        if (Yii::$app->user->isGuest) {
            return false;
        }

        $amoeba = Amoeba::findOne(['code' => $params['amoeba_id']]);
        if (is_null($amoeba)) {
            return false;
        }

        $inviteCode = UserInviteCode::find()->where([
            'user_id' => $user->id,
            'amoeba_id' => $amoeba->id,
        ])->one();
        if (is_null($inviteCode)) {
            $inviteCode = new UserInviteCode();
            $inviteCode->user_id = $user->id;
            $inviteCode->amoeba_id = $amoeba->id;
            $inviteCode->code = Yii::$app->security->generateRandomString(12);
            $inviteCode->save();
        }


        Yii::$app->response->format = Response::FORMAT_RAW;
        Yii::$app->response->headers->add('Content-Type', $qr->getContentType());


        return $qr
            // ->useLogo(Yii::getAlias('@frontend') . '/images/logo.jpg')
            // ->setLogoWidth(10)
            ->setText(FRONTEND_BASE_URL . '/user/signup?c=' . $inviteCode->code)
            ->setLabel(Yii::t('app.c2', 'My QRCode'))
            ->writeString();
    }
}